package com.eorchis.module.trainneedscope.ui.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eorchis.core.page.commond.JSONObject;
import com.eorchis.core.service.IBaseService;
import com.eorchis.core.servicetemplate.treetemplate.jsonbean.JsonTreeBean;
import com.eorchis.core.springext.mvc.SessionConstant;
import com.eorchis.core.ui.commond.ResultState;
import com.eorchis.core.ui.controller.AbstractBaseController;
import com.eorchis.module.TrainingConstants;
import com.eorchis.module.basedata.domain.BaseData;
import com.eorchis.module.basedata.service.cache.BaseDataCacheUtil;
import com.eorchis.module.department.domain.Department;
import com.eorchis.module.department.domain.DepartmentTreeCondition;
import com.eorchis.module.department.service.IDepartmentTreeService;
import com.eorchis.module.department.ui.commond.DepartmentTreeCommond;
import com.eorchis.module.trainingclass.domain.BaseDataQueryBean;
import com.eorchis.module.trainneedscope.domain.QueryClassUserBean;
import com.eorchis.module.trainneedscope.domain.TrainNeedScopeQueryBean;
import com.eorchis.module.trainneedscope.service.ITrainNeedScopeService;
import com.eorchis.module.trainneedscope.ui.commond.TrainNeedScopeQueryCommond;
import com.eorchis.module.trainneedscope.ui.commond.TrainNeedScopeValidCommond;
import com.eorchis.utils.JSONUtils;
import com.eorchis.utils.utils.PropertyUtil;

/**
 * Title: TrainNeedScopeController<br>
 * Description: 培训需求调查对象管理控制器<br>
 * Company: GoldGov<br>
 * Copyright @ 2012 GoldGov .All rights reserved.<br>
 * @author Max
 * @createDate 2014-08-27
 * @version $Revision$
 */
@Controller("trainNeedScopeController")
@RequestMapping(value = TrainNeedScopeController.MODULE_PATH)
public class TrainNeedScopeController 
		extends AbstractBaseController<TrainNeedScopeValidCommond,TrainNeedScopeQueryCommond> 
{
	// 模块页面根路径
	public static final String MODULE_PATH = "/module/trainneedscope";
	// 培训需求调查对象接口
	@Autowired
	@Qualifier("com.eorchis.module.trainneedscope.service.impl.TrainNeedScopeServiceImpl")
	private ITrainNeedScopeService trainNeedScopeService;
	
	@Autowired
    @Qualifier("com.eorchis.module.department.service.impl.DepartmentTreeServiceImpl")
    private IDepartmentTreeService departmentTreeService;
	
	@Resource(name = "com.eorchis.module.basedata.service.cache.BaseDataCacheUtil")
	private BaseDataCacheUtil baseDataCacheUtil;
	
	public IBaseService getService() {
		return trainNeedScopeService;
	}

	public String getModulePath() {
		return MODULE_PATH;
	}
	
	/**
	 * 查询问卷下用户列表
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author Max
	 * @createDate 2014-08-27
	 */
	@RequestMapping(value = "/getUserListByTrainNeedScope")
	public String getUserListByTrainNeedScope(
			@ModelAttribute("result") TrainNeedScopeQueryCommond qCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState
			) throws Exception {
		
		List<TrainNeedScopeQueryBean> list=trainNeedScopeService.getUserListByTrainNeedScope(qCommond);
		qCommond.setResultList(list);
		resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		return "";
	}
	
	/**
	 * 查询问卷列表下的部门列表
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author Max
	 * @createDate 2014-08-27
	 */
	@RequestMapping(value = "/getDeptListByTrainNeedScope")
	public String getDeptListByTrainNeedScope(
			@ModelAttribute("result") TrainNeedScopeQueryCommond qCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState
			) throws Exception {
		List<TrainNeedScopeQueryBean> list=trainNeedScopeService.getDeptListByTrainNeedScope(qCommond);
		qCommond.setResultList(list);
		resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		return "";
	}
	
	
	/**
	 * 查询问卷列表未选择人员
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author Max
	 * @createDate 2014-08-27
	 */
	@RequestMapping(value = "/findNoSelectedUserList")
	public String findNoSelectedUserList(
			@ModelAttribute("result") TrainNeedScopeQueryCommond qCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState
			) throws Exception {
		
		//查询treePath
		if(qCommond.getSearchDepId()!=null&&!"".equals(qCommond.getSearchDepId())) {
			DepartmentTreeCondition condition = new DepartmentTreeCondition();
			condition.setSearchDepID(qCommond.getSearchDepId());
			Department dept=departmentTreeService.getDepartment(condition);
			qCommond.setSearchTreePath(dept.getTreepath());
			Department department = (Department) request.getSession()
					.getAttribute(SessionConstant.CURRENT_SCOPE);
			if(qCommond.getSearchDepId()!=null&&department.getDeptID().equals(qCommond.getSearchDepId())) {
				qCommond.setSearchCurrDeptId(qCommond.getSearchDepId());
			}else if(qCommond.getSearchDepId()!=null&&department.getParentID().equals(qCommond.getSearchDepId())) {
				qCommond.setSearchCurrPardId(department.getDeptID());
				qCommond.setSearchTreePath(department.getTreepath());
			}
		}else {
			resultState.setState(ResultState.RESULT_STATE_FAIL);
			resultState.setMessage("部门ID为空");
			return "";
		}
		
		List<QueryClassUserBean> list=trainNeedScopeService.findNoSelectedUserList(qCommond);
		qCommond.setResultList(list);
		resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		return "";
	}
	
	
	/**
	 * 添加人员或部门到指标范围
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author Max
	 * @createDate 2014-08-12
	 */
	@RequestMapping(value = "/addEntityIntoTrainNeedScope")
	public String addEntityIntoTrainNeedScope(
			@ModelAttribute("result") TrainNeedScopeValidCommond  vCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState
			) throws Exception {
		Boolean state=trainNeedScopeService.addEntityIntoTrainNeedScope(vCommond);
		if(state) {
			resultState.setMessage("添加成功");
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		}else {
			resultState.setMessage("添加失败");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
		return "";
	}
	
	
	/**
	 * 根据管理范围查询组织机构树
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author Max
	 * @createDate 2014-08-12
	 */
	@RequestMapping(value = "/findDepartmentTree")
	public @ResponseBody
	  String findDepartmentTree(DepartmentTreeCommond commond,HttpServletRequest request,HttpServletResponse response) throws Exception {
		List<JsonTreeBean> result = new ArrayList<JsonTreeBean>();
		//取出当前管理范围
		if(!PropertyUtil.objectNotEmpty(commond.getNode())||commond.getNode().equals(JsonTreeBean.ROOT_NODE_PARENT_ID)){
			Department department = (Department) request.getSession()
					.getAttribute(SessionConstant.CURRENT_SCOPE);
			commond.setNode(department.getDeptID());
			DepartmentTreeCondition condition = new DepartmentTreeCondition();
			BeanUtils.copyProperties(commond, condition);
			condition.setFindLeapNode(true);
			JsonTreeBean rootBean = new JsonTreeBean();
			rootBean.setText("组织机构");
			rootBean.setLeaf(false);
			rootBean.setId(department.getParentID());
			rootBean.setState("close");
			rootBean.setExpandable(true);
			result.add(rootBean);
		} else {
			DepartmentTreeCondition condition = new DepartmentTreeCondition();
			BeanUtils.copyProperties(commond, condition);
			Department department = (Department) request.getSession()
					.getAttribute(SessionConstant.CURRENT_SCOPE);
			 if(commond.getNode().equals(department.getParentID())){
				JsonTreeBean rootBean = new JsonTreeBean();
				rootBean.setText(department.getDeptName());
				rootBean.setLeaf(false);
				rootBean.setId(department.getDeptID());
				rootBean.setState("close");
				rootBean.setExpandable(true);
				result.add(rootBean);
			}else {
				condition.setFindLeapNode(true);
				result = departmentTreeService
						.doProcess(condition);
			}
		}
		String jsonpcallback = request.getParameter("callback");
		if (result!=null&&!result.isEmpty()) {
			if (PropertyUtil.objectNotEmpty(jsonpcallback)) {
					response.getOutputStream().write((jsonpcallback+"("+JSONUtils.objToJson(result)+")").getBytes("UTF-8"));
			}else {
					response.getOutputStream().write((JSONUtils.objToJson(result)).getBytes("UTF-8"));
			}
		}else {
			if (PropertyUtil.objectNotEmpty(jsonpcallback)) {
					response.getOutputStream().write((jsonpcallback+"([])").getBytes("UTF-8"));
			}else {
					response.getOutputStream().write(("[]").getBytes("UTF-8"));
			}
		}
		return null;
	}
	
	
	/**
	 * 获取指标下职级的选择情况
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @author Max
	 * @throws Exception 
	 * @date 2014-08-15
	 */
	@RequestMapping(value="/getBaseListByTypeCode")
	public @ResponseBody JSONObject getBaseDList(Model model,HttpServletRequest request,   
			HttpServletResponse response) throws Exception{
		String  typeCode = TrainingConstants.LEVEL_CODE;
		String levelCodes=request.getParameter("levelCodes");
		JSONObject jsonResult = new JSONObject();
		if(typeCode != null){
			Map<String,List<BaseData>> baseDataMap =  baseDataCacheUtil.getBaseDataList();
			List<BaseData>  baseDataList = baseDataMap.get(typeCode);
			List<BaseDataQueryBean>  baseDQ=new ArrayList<BaseDataQueryBean>();
			for(int i=0;i<baseDataList.size();i++) {
				BaseData basedata=baseDataList.get(i);
				BaseDataQueryBean qb=new BaseDataQueryBean();
				BeanUtils.copyProperties(basedata, qb);
				if(PropertyUtil.objectNotEmpty(levelCodes)) {
					String [] ls=levelCodes.split(",");
					int z=0;
					for(int j=0;j<ls.length;j++) {
						if(basedata.getDataCode().equals(ls[j])) {
							qb.setIsSelect(1);//已选择
						}else {
							z=z+1;
							if(z==ls.length) {
								qb.setIsSelect(2);
							}
						}
					}
				}else {
					qb.setIsSelect(2);//未选择
				}
				
				baseDQ.add(qb);
			}
			
			jsonResult.setData(baseDQ);
			if(baseDataList != null){
				jsonResult.setTotalCount(baseDQ.size());
			}
			jsonResult.setSuccess(true);
		}else{
			jsonResult.setMsg("编码为空");
			jsonResult.setSuccess(false);
		}
		//return jsonResult;
		
		String jsonpcallback = request.getParameter("callback");
		if (jsonResult!=null) {
			if (PropertyUtil.objectNotEmpty(jsonpcallback)) {
					response.getOutputStream().write((jsonpcallback+"("+JSONUtils.objToJson(jsonResult)+")").getBytes("UTF-8"));
			}else {
					response.getOutputStream().write((JSONUtils.objToJson(jsonResult)).getBytes("UTF-8"));
			}
		}else {
			if (PropertyUtil.objectNotEmpty(jsonpcallback)) {
					response.getOutputStream().write((jsonpcallback+"([])").getBytes("UTF-8"));
			}else {
					response.getOutputStream().write(("[]").getBytes("UTF-8"));
			}
		}
		return null;
	}
	
	
	/**
	 * 查询未添加部门
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author Max
	 * @createDate 2014-08-12
	 */
	@RequestMapping(value = "/findNoSelectedDeptList")
	public String findNoSelectedDeptList(
			@ModelAttribute("result") TrainNeedScopeQueryCommond qCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState
			) throws Exception {
		
		//查询treePath
		if(qCommond.getSearchDepId()!=null&&!"".equals(qCommond.getSearchDepId())) {
			DepartmentTreeCondition condition = new DepartmentTreeCondition();
			condition.setSearchDepID(qCommond.getSearchDepId());
			Department dept=departmentTreeService.getDepartment(condition);
			Department department = (Department) request.getSession()
					.getAttribute(SessionConstant.CURRENT_SCOPE);
			qCommond.setSearchTreePath(dept.getTreepath());
			if(qCommond.getSearchDepId()!=null&&department.getDeptID().equals(qCommond.getSearchDepId())) {
				qCommond.setSearchCurrDeptId(qCommond.getSearchDepId());
			}else if(qCommond.getSearchDepId()!=null&&department.getParentID().equals(qCommond.getSearchDepId())) {
				qCommond.setSearchCurrPardId(department.getDeptID());
				qCommond.setSearchTreePath(department.getTreepath());
			}
		}else {
			resultState.setState(ResultState.RESULT_STATE_FAIL);
			resultState.setMessage("部门ID为空");
			return "";
		}
		
		List<QueryClassUserBean> list=trainNeedScopeService.findNoSelectedDeptList(qCommond);
		qCommond.setResultList(list);
		resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		return "";
	}
	
	
	/**
	 * 删除指标范围
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author Max
	 * @createDate 2014-08-12
	 */
	@RequestMapping(value = "/deleteTargetScopeLink")
	public String deleteTargetScopeLink(
			@ModelAttribute("result") TrainNeedScopeValidCommond  vCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState
			) throws Exception {
		
		if(vCommond.getSearchLinkIds()!=null&&vCommond.getSearchLinkIds().length>0) {
			trainNeedScopeService.deleteTargetScopeLink(vCommond);
			resultState.setMessage("删除成功");
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		}else {
			resultState.setMessage("未传入删除对象");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
		return "";
	}
	
	
	/**
	 * 修改职级
	 * @param commond
	 * @return
	 * @throws Exception
	 * @author Max
	 * @createDate 2014-08-12
	 */
	@RequestMapping(value = "/updateTargerScopeDuty")
	public String updateTargerScopeDuty(
			@ModelAttribute("result") TrainNeedScopeValidCommond  vCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState
			) throws Exception {
		if(vCommond.getSearchLinkId()!=null&&!"".equals(vCommond.getSearchLinkId())) {
			trainNeedScopeService.updateTargerScopeDuty(vCommond);
			resultState.setMessage("修改成功");
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		}else {
			resultState.setMessage("未传入修改对象");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
		return "";
	}
}
